package service

import (
	"sysu-giep/internal/database/models"

	"gorm.io/gorm"
)

type AdminService struct {
	db *gorm.DB
}

func NewAdminService(db *gorm.DB) *AdminService {
	return &AdminService{
		db: db,
	}
}

// GetUsers 获取所有用户列表
func (s *AdminService) GetUsers(page, size int, role, status string) ([]models.User, int64, error) {
	var users []models.User
	var total int64

	query := s.db.Model(&models.User{})

	// 角色筛选
	if role != "" {
		query = query.Where("role = ?", role)
	}

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Offset(offset).Limit(size).Find(&users).Error; err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// UpdateUserStatus 更新用户状态
func (s *AdminService) UpdateUserStatus(userID uint, status models.UserStatus) error {
	return s.db.Model(&models.User{}).Where("id = ?", userID).Update("status", status).Error
}

// GetProjects 获取所有课题列表
func (s *AdminService) GetProjects(page, size int, status string) ([]models.Project, int64, error) {
	var projects []models.Project
	var total int64

	query := s.db.Model(&models.Project{})

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Creator").
		Offset(offset).
		Limit(size).
		Find(&projects).Error; err != nil {
		return nil, 0, err
	}

	return projects, total, nil
}

// UpdateProjectStatus 更新课题状态
func (s *AdminService) UpdateProjectStatus(projectID uint, status models.ProjectStatus) error {
	return s.db.Model(&models.Project{}).Where("id = ?", projectID).Update("status", status).Error
}

// GetApplications 获取所有申请列表
func (s *AdminService) GetApplications(page, size int, status string) ([]models.Application, int64, error) {
	var applications []models.Application
	var total int64

	query := s.db.Model(&models.Application{})

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("Applicant").
		Preload("Reviewer").
		Offset(offset).
		Limit(size).
		Find(&applications).Error; err != nil {
		return nil, 0, err
	}

	return applications, total, nil
}

// UpdateApplicationStatus 更新申请状态
func (s *AdminService) UpdateApplicationStatus(applicationID uint, status models.ApplicationStatus, feedback string) error {
	updates := map[string]interface{}{
		"status": status,
	}

	if feedback != "" {
		updates["feedback"] = feedback
	}

	return s.db.Model(&models.Application{}).Where("id = ?", applicationID).Updates(updates).Error
}

// GetStatistics 获取平台统计信息
func (s *AdminService) GetStatistics() (map[string]interface{}, error) {
	statistics := make(map[string]interface{})

	// 用户统计
	var totalUsers int64
	if err := s.db.Model(&models.User{}).Count(&totalUsers).Error; err != nil {
		return nil, err
	}
	statistics["total_users"] = totalUsers

	// 角色分布
	var roleDistribution []struct {
		Role  string `json:"role"`
		Count int64  `json:"count"`
	}
	if err := s.db.Model(&models.User{}).
		Select("role, count(*) as count").
		Group("role").
		Scan(&roleDistribution).Error; err != nil {
		return nil, err
	}
	statistics["user_distribution"] = roleDistribution

	// 课题统计
	var totalProjects int64
	if err := s.db.Model(&models.Project{}).Count(&totalProjects).Error; err != nil {
		return nil, err
	}
	statistics["total_projects"] = totalProjects

	// 课题状态分布
	var projectStatusDistribution []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	if err := s.db.Model(&models.Project{}).
		Select("status, count(*) as count").
		Group("status").
		Scan(&projectStatusDistribution).Error; err != nil {
		return nil, err
	}
	statistics["project_distribution"] = projectStatusDistribution

	// 申请统计
	var totalApplications int64
	if err := s.db.Model(&models.Application{}).Count(&totalApplications).Error; err != nil {
		return nil, err
	}
	statistics["total_applications"] = totalApplications

	// 申请状态分布
	var applicationStatusDistribution []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	if err := s.db.Model(&models.Application{}).
		Select("status, count(*) as count").
		Group("status").
		Scan(&applicationStatusDistribution).Error; err != nil {
		return nil, err
	}
	statistics["application_distribution"] = applicationStatusDistribution

	// 匹配统计
	var totalMatches int64
	if err := s.db.Model(&models.ProjectMatch{}).Count(&totalMatches).Error; err != nil {
		return nil, err
	}
	statistics["total_matches"] = totalMatches

	return statistics, nil
}
